import { useCallback } from 'react';
import { DynamicCrudPage } from '@/components';
import type { TableConfig } from '@/components/DynamicTable/types';
import { getTableConfigByCode } from '@/api/tableConfig';
import { transformTableConfig } from '@/utils/tableConfigTransform';
import { transformEditData, transformSubmitData } from '@/utils/formDataTransform';
import { getTenants, createTenant, updateTenant, deleteTenant } from './api';

const TenantManagement = () => {
  // 获取表配置
  const fetchConfigApi = useCallback(async (): Promise<TableConfig> => {
    const configRecord = await getTableConfigByCode('tenants');
    if (!configRecord) {
      throw new Error('租户表格配置不存在');
    }
    return transformTableConfig(configRecord);
  }, []);

  // 数据转换 - 提交时清理不需要的字段
  const handleTransformFormData = (data: any, mode: 'create' | 'update') => {
    return transformSubmitData(data, ['plan']); // 排除 plan 关联对象
  };

  // 数据转换 - 编辑时提取关联对象的ID
  const handleTransformEditData = (data: any) => {
    const editData = transformEditData(data);
    
    // 处理 plan 关联
    if (editData.plan && typeof editData.plan === 'object') {
      editData.planId = editData.plan.id;
    }
    
    return editData;
  };

  return (
    <DynamicCrudPage
      fetchConfigApi={fetchConfigApi}
      fetchApi={getTenants}
      createApi={createTenant}
      updateApi={updateTenant}
      deleteApi={deleteTenant}
      transformEditData={handleTransformEditData}
      transformFormData={handleTransformFormData}
      title="租户管理"
      scroll={{ x: 1200 }}
      formWidth={600}
    />
  );
};

export default TenantManagement;
